package com.wanghui.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wanghui.reggie.common.R;
import com.wanghui.reggie.entity.User;
import com.wanghui.reggie.service.UserService;
import com.wanghui.reggie.utils.SMSUtils;
import com.wanghui.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //随机生成4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码：{}", code);   //控制台输出，模拟使用短信发送验证码
            //将验证码发送给指定用户
            //SMSUtils.sendMessage("瑞吉外卖", "", phone, code);

            //将验证码保存到session中，用于在后面登录时进行登录验证
            //httpSession.setAttribute(phone, code);
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);  //第四个参数：设置过期参数的时间单位——分钟
            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 移动端用户登录
     *
     * @param map
     * @param httpSession
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession httpSession) {
        //获取电话号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从session中获取保存的验证码
        //String codeSession = httpSession.getAttribute(phone).toString();

        //从redis中获取缓存的验证码
        Object codeSession = redisTemplate.opsForValue().get(phone);

        //验证码比较
        if (codeSession != null && codeSession.equals(code)) {
            //查询user表中是否存在用户信息，不存在则进行注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                //user表中没有用户信息，进行注册(id值有mybatisPlus提供的雪花算法自动生成)
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            //这里存入session是为了让其在过滤器中通过校验放行
            httpSession.setAttribute("user", user.getId()); //将userid存入session
            redisTemplate.delete(phone);    //登录成功后，则删除redis中的验证码
            return R.success(user);
        }

        //如果失败，返回失败信息
        return R.error("登录失败");
    }
}
